package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.CommentApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.vo.CommentVo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.PageResult;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class CommentService {
    @DubboReference
    private CommentApi commentApi;
    @DubboReference
    private UserInfoApi userInfoApi;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    public void saveComments(String movementId, String content) {
        //1、获取操作用户id
        Long userId = UserHolder.getUserId();
        //判断是否被冻结
        String FreezingValue = redisTemplate.opsForValue().get(Constants.FreezingRange_SAY + userId);
        if (FreezingValue != null) {
            if ("never".equals(FreezingValue)) {
                throw new BusinessException(ErrorResult.FreezingSayNeverError());
            }
            //获取当前时间毫秒值
            long NowTime = new Date().getTime();
            //获取冻结结束时间
            Long FreezingTime = Long.valueOf(FreezingValue);
            //(unFreezingHour)距离解封时间还有多少小时
            Long unFreezingHour = (FreezingTime - NowTime) / 1000 / 3600;
            throw new BusinessException(ErrorResult.FreezingSayTimeError(unFreezingHour.toString()));
        }
        //2、构造Comment
        Comment comment=new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(CommentType.COMMENT.getType());
        comment.setContent(content);
        comment.setUserId(userId);
        comment.setCreated(System.currentTimeMillis());
        //3、调用API保存评论
        Integer counts=commentApi.save(comment);
        log.info("counts="+counts);
    }
    //评论列表
    public PageResult commentList(String movementId, int page, int pagesize) {
        //调用api,获取评论列表
        List<Comment> comments=commentApi.commentList(movementId,CommentType.COMMENT,page,pagesize);
        //判断列表是否存在
        if(CollUtil.isEmpty(comments)){
            //如果为空返回分页对象
            return new PageResult();
        }
        //提取所有用户id,调用UserInfoApi获取用户详情
        List<Long> userIds = CollUtil.getFieldValues(comments, "userId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);
        //构建vo对象
        List<CommentVo> vos=new ArrayList<>();
        for (Comment comment : comments) {
            //根据userId获取用户详情
            UserInfo userInfo = map.get(comment.getUserId());
            //转化为vo对象
            CommentVo vo = CommentVo.init(userInfo, comment);
            String key = Constants.MOVEMENTS_INTERACT_KEY + comment.getId();
            String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
            String redisValue= (String) redisTemplate.opsForHash().get(key, hashKey);
            if (redisValue!=null){
                vo.setHasLiked(1);
            }
            vos.add(vo);
        }
        //构建返回值
        PageResult pr = new PageResult(page, pagesize, 0l, vos);
        return pr;
    }

    public Integer like(String id) {
        Long userId = UserHolder.getUserId();
        //调用api,查询是否已经点赞
        Boolean flag=commentApi.like(id,userId,CommentType.LIKE);
        //如果已经点赞,自定义异常
        if(flag){
            throw new BusinessException(ErrorResult.likeError());
        }
        //没有点赞,调用api保存数据到MongoDB
        Comment comment=new Comment();
        comment.setUserId(userId);
        comment.setPublishId(new ObjectId(id));
        comment.setCommentType(CommentType.LIKE.getType());
        comment.setCreated(System.currentTimeMillis());
        //保存数据
        Integer count = commentApi.save(comment);
        //拼接Redis的key,将用户点赞动态保存到Redis
        String key= Constants.MOVEMENTS_INTERACT_KEY+id;
        String hashKey=Constants.MOVEMENT_LIKE_HASHKEY+userId;
        redisTemplate.opsForHash().put(key,hashKey,"1");
        return count;
    }

    public Integer disLike(String id) {
        Long userId = UserHolder.getUserId();
        //调用api,查询是否已经点赞
        Boolean flag=commentApi.like(id,userId,CommentType.LIKE);
        //如果没有点赞,自定义异常
        if(!flag){
            throw new BusinessException(ErrorResult.disLikeError());
        }
        //没有点赞,调用api删除数据
        Comment comment=new Comment();
        comment.setUserId(userId);
        comment.setPublishId(new ObjectId(id));
        comment.setCommentType(CommentType.LIKE.getType());
        //删除数据
        Integer count = commentApi.delete(comment);
        //拼接Redis的key,将用户点赞动态删除
        String key= Constants.MOVEMENTS_INTERACT_KEY+id;
        String hashKey=Constants.MOVEMENT_LIKE_HASHKEY+userId;
        redisTemplate.opsForHash().delete(key,hashKey);
        return count;
    }

    public Integer love(String id) {
        //调用api,查询是否已经喜欢
        Long userId = UserHolder.getUserId();
        Boolean flag = commentApi.like(id, userId, CommentType.LOVE);
        //如果已经喜欢,自定义异常
        if(flag){
            throw new BusinessException(ErrorResult.loveError());
        }
        //没有喜欢,调用api保存数据
        Comment comment=new Comment();
        comment.setPublishId(new ObjectId(id));
        comment.setUserId(userId);
        comment.setCommentType(CommentType.LOVE.getType());
        comment.setCreated(System.currentTimeMillis());
        //保存数据
        Integer count = commentApi.save(comment);
        //拼接Redis的key,将用户喜欢动态保存到Redis
        String key= Constants.MOVEMENTS_INTERACT_KEY+id;
        String hashKey=Constants.MOVEMENT_LOVE_HASHKEY+userId;
        redisTemplate.opsForHash().put(key,hashKey,"1");
        return count;
    }

    public Integer unlove(String id) {
        //调用api,查询是否已经喜欢
        Long userId = UserHolder.getUserId();
        Boolean flag = commentApi.like(id, userId, CommentType.LOVE);
        //如果没有喜欢,自定义异常
        if(!flag){
            throw new BusinessException(ErrorResult.disloveError());
        }
        //没有喜欢,调用api删除数据
        Comment comment=new Comment();
        comment.setPublishId(new ObjectId(id));
        comment.setUserId(userId);
        comment.setCommentType(CommentType.LOVE.getType());
        //删除数据
        Integer count = commentApi.delete(comment);
        //拼接Redis的key,将用户喜欢动态删除
        String key= Constants.MOVEMENTS_INTERACT_KEY+id;
        String hashKey=Constants.MOVEMENT_LOVE_HASHKEY+userId;
        redisTemplate.opsForHash().delete(key,hashKey);
        return count;
    }

    public Integer commentLike(String commentId) {
        //1、调用API查询用户是否已点赞
        Boolean hasContent = commentApi.hasContent(commentId,UserHolder.getUserId());
        if (hasContent) {
            throw new BusinessException(ErrorResult.likeError());
        }
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(commentId));
        comment.setUserId(UserHolder.getUserId());
        comment.setCreated(System.currentTimeMillis());
        Integer count = commentApi.saveCL(comment);
        String key = Constants.MOVEMENTS_INTERACT_KEY + commentId;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().put(key,hashKey,"1");
        return count;
    }

    public Integer disLikeComment(String commentId) {
        //1、调用API查询用户是否已点赞
        Boolean hasContent = commentApi.hasContent(commentId,UserHolder.getUserId());
        if (!hasContent) {
            throw new BusinessException(ErrorResult.disLikeError());
        }
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(commentId));
        comment.setUserId(UserHolder.getUserId());
        comment.setCreated(System.currentTimeMillis());
        Integer count = commentApi.deleteCL(comment);
        String key = Constants.MOVEMENTS_INTERACT_KEY + commentId;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().delete(key,hashKey);
        return count;
    }
}
